#include "stdafx.h"
#include "GSE_CSql.h"
#include "GSE_CMysqlConnection.h"
namespace GSE
{
	boost::mutex mSql;
	CSql * CSql::m_pInstance = NULL;

	ISql * ISql::CreateModule()
	{
		if ( NULL == CSql::m_pInstance)
		{
			boost::lock_guard<boost::mutex> guard(mSql);
			if ( NULL == CSql::m_pInstance )
			{
				CSql::m_pInstance = new CSql;
			}
		}
		return CSql::m_pInstance;
	}
	void ISql::DestroyModule()
	{
		boost::lock_guard<boost::mutex> guard(mSql);
		delete CSql::m_pInstance;
		CSql::m_pInstance = NULL;
	}

	ISql * ISql::InstancePtr()
	{
		return CreateModule();
	}

	ISqlConnection * CSql::CreateConnection(BACKEND_TYPE _Type)
	{
		static uint32 index = 0;
		ISqlConnection	* conn = NULL;
		boost::lock_guard<boost::mutex> guard(mSql);
		if (_Type == MYSQL_DB)
		{
			CMysqlConnection * lpMysqlConnection = new CMysqlConnection(index,this);
			if (NULL != lpMysqlConnection)
			{
				mConnetions[lpMysqlConnection] = std::pair<uint,boost::function<bool ()>>(index++,boost::bind(&CMysqlConnection::Run,lpMysqlConnection));
			}
			conn = lpMysqlConnection;
		}
		else if (_Type == POSTGRESQL_DB)
		{
#ifdef ENABLE_POSTGRESQL
			conn = new postgresql_connection(this,index);
#else
			conn = NULL;
#endif
		}
		return conn;
	}

	void CSql::DestroyConnection(ISqlConnection * _Conn)
	{
		ConnectionList::iterator i = mConnetions.find(_Conn);
		if (i != mConnetions.end())
		{
			mConnetions.erase(i);
		}
	}

	uint CSql::Run()
	{
		for ( auto i = mConnetions.begin(); i != mConnetions.end(); ++i )
		{
			i->second.second();
		}
		return 0;
	}
}